package com.guodi.common.utils;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.Set;

public class IPAddressUtil {
    private IPAddressUtil() {
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip.contains(",") ? ip.split(",")[0] : ip;
    }

    public static String getLocalIp() {
        String localIp = null;

        try {
            InetAddress address = InetAddress.getLocalHost();
            if (address != null) {
                localIp = address.getHostAddress();
            }
        } catch (UnknownHostException var2) {
            var2.printStackTrace();
        }

        return localIp;
    }

    public static String getLocalPort() {
        String port = "";

        try {
            MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
            Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
            port = ((ObjectName)objectNames.iterator().next()).getKeyProperty("port");
        } catch (MalformedObjectNameException var3) {
            var3.printStackTrace();
        }

        return port;
    }

    public static String getOsName() {
        Properties props = System.getProperties();
        return props.getProperty("os.name");
    }
}
